/*
 * All content copyright http://www.j2eefast.com, unless
 * otherwise indicated. All rights reserved.
 * No deletion without permission
 */
package com.j2eefast.web.service;

import cn.hutool.core.thread.GlobalThreadPool;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.j2eefast.web.common.BaseUrl;
import com.j2eefast.web.entity.ClassifyEntity;
import com.j2eefast.web.entity.SpuEntity;
import com.j2eefast.web.mapper.SpuMapper;
import com.j2eefast.common.core.page.Query;
import com.j2eefast.common.core.utils.PageUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.framework.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;

/**
 * 【请填写功能名称】Service接口
 * @author: ZhouZhou
 * @date 2021-06-11 10:29:56
 */
@Service
public class SpuService extends ServiceImpl<SpuMapper,SpuEntity> {

	@Resource
	private SpuMapper spuMapper;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private ClassifyService classifyService;

	@Autowired
	private ShopService shopService;

	@Autowired
	private SkuService skuService;

	public void initSpus() {
		List<ClassifyEntity> classifies = classifyService.getThreeClassify();

		String token = loginService.getToken();

		System.out.println("开始抓取商品信息");
		Long startTime = System.currentTimeMillis();
		for (ClassifyEntity c : classifies) {
			saveData(c.getId(), token);
			System.out.println("完成分类:" + c.getName());

		}

		System.out.println("完成商品初始化");
		System.out.println(String.format("共计耗时：%s秒", (System.currentTimeMillis() - startTime) / 1000));

	}

	private void saveData(Integer classifyId, String token) {
		// 默认从第一页开始取数
		String url = BaseUrl.getGetItemsByClassifyId(classifyId, 1);
		JSONObject data = doRequest(url, token);
		Integer totalPage = data.getInt("totalPage");

		if (totalPage <= 0) {
			return;
		}

		saveData(data.getJSONArray("data"), token);

		if (totalPage > 1) {// 获取其他页码数据
			for (int i = 2; i <= totalPage; i++) {
				url = BaseUrl.getGetItemsByClassifyId(classifyId, i);
				data = doRequest(url, token);

				saveData(data.getJSONArray("data"), token);
			}
		}
	}

	private void saveData(JSONArray array, String token) {
		for (int i = 0; i < array.size(); i++) {
			JSONObject o = array.getJSONObject(i);
			SpuEntity spu = getSpu(o);

			CountDownLatch countDownLatch = new CountDownLatch(3);
			GlobalThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					// 保存SPU
					saveData(spu);
					countDownLatch.countDown();
				}
			});

			GlobalThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					// 保存SKU数据
					saveSkuData(o.getJSONArray("itemSkus"), token);
					countDownLatch.countDown();
				}
			});

			GlobalThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					// 保存供应商数据
					saveShopData(spu.getShopId());
					countDownLatch.countDown();
				}
			});

			try {
				countDownLatch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void saveShopData(Long shopId) {
		shopService.saveShop(shopId);
	}

	private void saveSkuData(JSONArray itemSkus, String token) {
		skuService.saveSkuData(itemSkus, token);
	}

	private void saveData(SpuEntity spu) {
		SpuEntity query = new SpuEntity();
		query.setId(spu.getId());

		List<SpuEntity> dataList = spuMapper.findList(query);
		if (dataList == null || dataList.size() == 0) {
			spuMapper.insert(spu);
		} else {
			SpuEntity existSpu = dataList.get(0);
			spu.setPkId(existSpu.getPkId());
			this.updateById(spu);
		}

	}

	private SpuEntity getSpu(JSONObject data) {
		SpuEntity s = new SpuEntity();
		s.setAddTime(data.getLong("addTime"));
		s.setBrandId(data.getInt("brandId"));
		s.setClassifyOne(data.getInt("classifyOne"));
		s.setClassifyOneName(data.getStr("classifyOneName"));
		s.setClassifyThree(data.getInt("classifyThree"));
		s.setClassifyThreeName(data.getStr("classifyThreeName"));
		s.setClassifyTwo(data.getInt("classifyTwo"));
		s.setFirstName(data.getStr("firstName"));
		s.setClassifyTwoName(data.getStr("classifyTwoName"));
		s.setId(data.getLong("id"));
		s.setImgsCover(data.getStr("imgsCover"));
		s.setIsHomeShow(data.getStr("isHomeShow"));
		s.setItemStatus(data.getInt("itemStatus"));
		s.setName(data.getStr("name"));
		s.setShopId(data.getLong("shopId"));

		JSONObject itemSpuSummary = data.getJSONObject("itemSpuSummary");
		if(itemSpuSummary != null) {
			s.setSpuVisits(itemSpuSummary.getLong("spuVisits"));
			s.setSpuSales(itemSpuSummary.getLong("spuSales"));
			s.setSpuComments(itemSpuSummary.getLong("spuComments"));
		}

		return s;
	}

	private JSONObject doRequest(String url, String token) {
		String result = HttpRequest.get(url).header("X-AIYANGNIU-SIGNATURE", token)
				.execute().body();

		return JSONUtil.parseObj(result);
	}

	/**
	 * mybaitis-plus 单表页面分页查询
     */
	public PageUtil findPage(Map<String, Object> params) {
		QueryWrapper<SpuEntity> queryWrapper = new QueryWrapper<SpuEntity>();
		String addTime = (String) params.get("addTime");
        queryWrapper.eq(ToolUtil.isNotEmpty(addTime), "add_time", addTime);
		String brandId = (String) params.get("brandId");
        queryWrapper.eq(ToolUtil.isNotEmpty(brandId), "brand_id", brandId);
		String classifyOne = (String) params.get("classifyOne");
        queryWrapper.eq(ToolUtil.isNotEmpty(classifyOne), "classify_one", classifyOne);
		String classifyOneName = (String) params.get("classifyOneName");
        queryWrapper.like(ToolUtil.isNotEmpty(classifyOneName), "classify_one_name", classifyOneName);
		String classifyThree = (String) params.get("classifyThree");
        queryWrapper.eq(ToolUtil.isNotEmpty(classifyThree), "classify_three", classifyThree);
		String classifyThreeName = (String) params.get("classifyThreeName");
        queryWrapper.like(ToolUtil.isNotEmpty(classifyThreeName), "classify_three_name", classifyThreeName);
		String classifyTwo = (String) params.get("classifyTwo");
        queryWrapper.eq(ToolUtil.isNotEmpty(classifyTwo), "classify_two", classifyTwo);
		String classifyTwoName = (String) params.get("classifyTwoName");
        queryWrapper.like(ToolUtil.isNotEmpty(classifyTwoName), "classify_two_name", classifyTwoName);
		String firstName = (String) params.get("firstName");
        queryWrapper.like(ToolUtil.isNotEmpty(firstName), "first_name", firstName);
		String imgsCover = (String) params.get("imgsCover");
        queryWrapper.eq(ToolUtil.isNotEmpty(imgsCover), "imgs_cover", imgsCover);
		String isHomeShow = (String) params.get("isHomeShow");
        queryWrapper.eq(ToolUtil.isNotEmpty(isHomeShow), "is_home_show", isHomeShow);
		String itemStatus = (String) params.get("itemStatus");
        queryWrapper.eq(ToolUtil.isNotEmpty(itemStatus), "item_status", itemStatus);
		String name = (String) params.get("name");
        queryWrapper.like(ToolUtil.isNotEmpty(name), "name", name);
		String shopId = (String) params.get("shopId");
        queryWrapper.eq(ToolUtil.isNotEmpty(shopId), "shop_id", shopId);
		String spuComments = (String) params.get("spuComments");
        queryWrapper.eq(ToolUtil.isNotEmpty(spuComments), "spu_comments", spuComments);
		String spuSales = (String) params.get("spuSales");
        queryWrapper.eq(ToolUtil.isNotEmpty(spuSales), "spu_sales", spuSales);
		String spuVisits = (String) params.get("spuVisits");
        queryWrapper.eq(ToolUtil.isNotEmpty(spuVisits), "spu_visits", spuVisits);
		Page<SpuEntity> page = spuMapper.selectPage(new Query<SpuEntity>(params).getPage(), queryWrapper);
		return new PageUtil(page);
    }

	/**
	 * 自定义分页查询，含关联实体对像
	 */
	public PageUtil findPage(Map<String, Object> params,SpuEntity spuEntity) {
		Page<SpuEntity> page = spuMapper.findPage(new Query<SpuEntity>(params).getPage(),
					spuEntity,
				(String) params.get(Constant.SQL_FILTER));
		return new PageUtil(page);
	}

	/**
	* 查列表
	*/
	public List<SpuEntity> findList(SpuEntity spuEntity){
		return spuMapper.findList(spuEntity);
	}

	/**
     * 批量删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteBatchByIds(Long[] ids) {
		return this.removeByIds(Arrays.asList(ids));
	}

	/**
     * 单个删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean delSpuById(Long pkId) {
		return this.removeById(pkId);
	}

	/**
     * 保存
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean addSpu(SpuEntity spu){
		if(this.save(spu)){
			return true;
		}
        return false;
    }

	/**
     * 修改根居ID
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean updateSpuById(SpuEntity spu) {
		if(this.updateById(spu)){
			return true;
		}
		return false;
	}

	/**
     * 根居ID获取对象
     */
	public SpuEntity findSpuById(Long pkId){
		return spuMapper.findSpuById(pkId);
	}


}
